package com.sky.advice;

import com.sky.annotation.AutoFill;
import com.sky.constant.AutoFillMethodNameConstant;
import com.sky.context.BaseContext;
import com.sky.emumeration.OperationType;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.time.LocalDateTime;

@Aspect
@Component
public class AutoFillAspect {
    @Pointcut("execution(* com.sky.mapper.*.*(..)) && @annotation(com.sky.annotation.AutoFill))")
    public void autoFillPt(){}

    @Before("autoFillPt()")
    public void before(JoinPoint joinPoint){
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature= (MethodSignature) signature;
        Method method = methodSignature.getMethod();
        AutoFill autoFill = method.getAnnotation(AutoFill.class);
        OperationType value = autoFill.value();
        Object[] args = joinPoint.getArgs();
        if (args == null&&args.length==0) {
            return;
        }
        Object parameter=args[0];
        if (value== OperationType.INSERT) {
            try {
                Method setCreateTime = parameter.getClass().getDeclaredMethod(AutoFillMethodNameConstant.SET_CREATE_TIME, LocalDateTime.class);
                Method setUpdateTime = parameter.getClass().getDeclaredMethod(AutoFillMethodNameConstant.SET_UPDATE_TIME, LocalDateTime.class);
                Method setCreateUser = parameter.getClass().getDeclaredMethod(AutoFillMethodNameConstant.SET_CREATE_USER, Long.class);
                Method setUpdateUser = parameter.getClass().getDeclaredMethod(AutoFillMethodNameConstant.SET_UPDATE_USER, Long.class);
                setCreateTime.invoke(parameter,LocalDateTime.now());
                setUpdateTime.invoke(parameter,LocalDateTime.now());
                setCreateUser.invoke(parameter, BaseContext.getEmpId());
                setUpdateUser.invoke(parameter,BaseContext.getEmpId());
            } catch (Exception e) {
                e.printStackTrace();
            }

        }else if (value== OperationType.UPDATE) {
            try {
                Method setUpdateTime = parameter.getClass().getDeclaredMethod(AutoFillMethodNameConstant.SET_UPDATE_TIME, LocalDateTime.class);
                Method setUpdateUser = parameter.getClass().getDeclaredMethod(AutoFillMethodNameConstant.SET_UPDATE_USER, Long.class);
                setUpdateTime.invoke(parameter,LocalDateTime.now());
                setUpdateUser.invoke(parameter,BaseContext.getEmpId());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
